<?PHP

class OP_ArchivesIndexWidget extends OP_WidgetTemplate{
	function render(){
		global $OnePress;		
		$title = empty( $this->values['title'] ) ? __( 'Archives' ) : apply_filters('widget_title', $values['title']);
		
		if(count($this->values['tabs'])>0){
			
			$feature_content = array();
			$count = 0;
			
			foreach($this->values['tabs'] as $tab){
				// Assign tab name
				$feature_content[$count]['name'] = ucwords($tab['sort']);
				
				// Add feature content to tab
				$archives = $this->get_archives($tab['sort']);
				$feature_content[$count]['content'] = $this->render_archives($archives);
				
				$count++; // Only increase count if we have added a tab
			}
		}
		
		include(TEMPLATEPATH.'/widgets/template.archives_index.php'); // Include widget template file
	}
	
	function render_archives($archives){
		$savemeta = NULL;
		$output = '';
		foreach($archives as $archive => $posts){
			if($archive != $savemeta){
				if($ulopen) $output .= '</ul>';
				$output .= '<h2>'.str_replace('-',' ',$archive).' ('.count($archives[$archive]).') </h2>';
				$output .= '<ul>';
				$savemeta = $archive;
				$ulopen = TRUE;
				foreach($posts as $post){
					$archive_link = get_archives_link($post['url'], $post['text'],'','','');
					$archive_link = isset($this->values['nofollow']) ? str_replace("'>","' rel=\"nofollow\">",$archive_link) : $archive_link;
					$date = date('M j',strtotime($post['date']));
					$output .= '<li>'.$date.': '.$archive_link.'</li>';
				}
			}
			
		}
		$output .= '</ul>';
		return $output;
	}
	
	function get_archives($sort){
		global $wpdb;
		
		//filters
		$where = apply_filters('getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r );
		$join = apply_filters('getarchives_join', "", $r);	
		
		$archives = array();
		if($sort == 'date'){
			$query = "SELECT * FROM $wpdb->posts $join $where ORDER BY post_date DESC $limit";

			$results = $wpdb->get_results($query);
			
			if($results){
				foreach($results as $result){
					if ( $result->post_date != '0000-00-00 00:00:00' ) {
						$url  = get_permalink($result);
						$post_title = $result->post_title;
						if ( $post_title )
							$text = strip_tags(apply_filters('the_title', $post_title));
						else
							$text = $result->ID;
						$date_key = date('F-Y',strtotime($result->post_date));
						$archives[$date_key][] = array('url'=>$url, 'text'=>$text, 'date'=>$result->post_date);
					}
				}
			}
		}
		else if($sort == 'author'){
			$query = "SELECT p.*,u.display_name as author_name FROM $wpdb->posts p
			JOIN $wpdb->users u ON p.post_author=u.ID
			WHERE p.post_type = 'post' AND p.post_status = 'publish'
			ORDER BY u.display_name ASC";
			
			$results = $wpdb->get_results($query);

			if($results){
				$oldlabel = NULL;
				foreach($results as $result){
					$url  = get_permalink($result);
					$post_title = $result->post_title;
					if ( $post_title )
						$text = strip_tags(apply_filters('the_title', $post_title));
					else
						$text = $result->ID;
					$archives[$result->author_name][] = array('url'=>$url, 'text'=>$text, 'date'=>$result->post_date);
				}
			}
		}
		else if($sort == 'alphabetical'){
			$query = "SELECT * FROM $wpdb->posts $join $where ORDER BY post_title ASC $limit";

			$results = $wpdb->get_results($query);
			
			if($results){
				foreach($results as $result){
					if ( $result->post_date != '0000-00-00 00:00:00' ) {
						$url  = get_permalink($result);
						$post_title = $result->post_title;
						if ( $post_title )
							$text = strip_tags(apply_filters('the_title', $post_title));
						else
							$text = $result->ID;
						$alph_key = substr($post_title,0,1);
						$archives[$alph_key][] = array('url'=>$url, 'text'=>$text, 'date'=>$result->post_date);
					}
				}
			}
		}
		else{ // Deal with tags, categories and featured together
			$where = '';
			if($sort == 'featured'){
				$where = "AND t.name='feature'";
				$sort = 'tag';
			}
			
			$type = $sort == 'tag' ? 'post_tag' : 'category';
			$query ="SELECT p.*, t.name FROM $wpdb->posts p
				JOIN $wpdb->term_relationships tr ON p.ID=tr.object_id
				JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id=tt.term_taxonomy_id
				JOIN $wpdb->terms t ON tt.term_id=t.term_id
				WHERE p.post_type = 'post' AND p.post_status = 'publish' AND tt.taxonomy='$type' $where 
				ORDER BY t.name ASC";
				
			$results = $wpdb->get_results($query);
			
			if($results){
				$oldlabel = NULL;
				foreach($results as $result){
					if ( $result->name != '' ) {
						$url  = get_permalink($result->ID);
						$post_title = $result->post_title;
						if ( $post_title )
							$text = strip_tags(apply_filters('the_title', $post_title));
						else
							$text = $result->ID;
						$archives[$result->name][] = array('url'=>$url, 'text'=>$text, 'date'=>$result->post_date);
					}
				}
			}
		}
		
		return $archives;
	}
	
	function do_post($post){
		$tabs = array();
		for($i = 0; $i < count($post['tab']['sort']); $i++){
			if($post['tab']['sort'][$i] == '') continue;
			
			$tabs[] = array(
				'sort'		=>	attribute_escape($post['tab']['sort'][$i])
			);
		}
		
		$title = attribute_escape($post['title']);
		$nofollow = isset($post['nofollow']);
		return array('tabs'=>$tabs,'title'=>$title,'nofollow'=>$nofollow);
	}

	function options(){
		$title = attribute_escape($this->values['title']);
		
		$options = array('alphabetical','author','date','tag','category','featured');
		
		echo '<p><label for="op_archives_index-title-'.$this->values['number'].'">'._e('Title:').' <input class="widefat" id="op_archives_index-title-'.$this->values['number'].'" name="widget_op_archives_index['.$this->values['number'].'][title]" type="text" value="'.$title.'" /></label></p>';
		
		echo '<div><a href="#" class="op_add_tab_trigger">+ Add Tab</a></div>',
			'<div class="tab_options" style="display:none">',
			'<a href="#" class="op_remove_tab_trigger">X</a>',
			'<label>Select sort type: </label><select name="widget_op_archives_index['.$this->values['number'].'][tab][sort][]">',
			'<option></option>';

		foreach($options as $option){
			echo '<option value="'.$option.'">'.$option.'</option>';
		}

		echo '</select>',
			'</div>';
			
		echo '<div class="op_current_tabs">';
		if(count($this->values['tabs'])>0){
			foreach($this->values['tabs'] as $tab){
				echo '<div class="tab_options">',
					'<a href="#" class="op_remove_tab_trigger">X</a>',
					'<label>Select sort type: </label><select name="widget_op_archives_index['.$this->values['number'].'][tab][sort][]">',
					'<option></option>';
					
				foreach($options as $option){
					$checked = $tab['sort'] == $option ? ' SELECTED' : '';
					echo '<option value="'.$option.'"'.$checked.'>'.$option.'</option>';
				}
				echo '</select>',
					'</div>';			
			}	
		}
		
		$nofollow = $this->values['nofollow'] ? 'checked="checked"' : '';
		
		echo '</div>',
			'</p>',
			'<label for="op_archives_index-nofollow">'._e('Make links "nofollow"').' </label> <input class="checkbox" type="checkbox" '.$nofollow.' id="op_archives_index-nofollow-'.$this->values['number'].'" name="widget_op_archives_index['.$this->values['number'].'][nofollow]" />';
	}
	
	/**
	 * Add styles and javascript for rendered widget
	 *
	 * @return void
	 * @author Sean
	 **/
	function head(){
		$url = get_bloginfo('template_directory').'/';
		wp_register_script('optabbedcontentjs', $url.'scripts/tabbed_content.js',array('onepressjs'));
		wp_enqueue_script('optabbedcontentjs');
	}
	
	/**
	 * Add styles and javascript for widget admin
	 *
	 * @return void
	 * @author Sean
	 **/
	function admin_head(){
		$url = get_bloginfo('template_directory').'/op/admin/';
		wp_register_script('opfeaturettetabsadminjs', $url.'scripts/featurette_tabs.js',array('jquery','jquery-ui-sortable'));
		wp_enqueue_script('opfeaturettetabsadminjs');
		wp_register_style('opfeaturettetabsadmin',$url.'styles/featurette_tabs.css');
		wp_enqueue_style('opfeaturettetabsadmin');
	}
}

$widget = new OP_Widget('archives_index');
$widget->setMeta('OP Archives Index','Display an index of your post archives');
$widget->setDefaults(array('title'=>'test','sort'=>'date','nofollow'=>FALSE,'tabs'=>array(array('sort'=>'date'))));
$widget->setAdminDimensions(415,350);

$opw_archives_index = new OP_ArchivesIndexWidget($widget);
add_action('widgets_init', array($opw_archives_index, 'init'));
?>